Popular Searches
Popular Course Categories
Popular Courses

Form Submission

Form Submission

React Forms

Form Submission in React JS

Form Submission in React JS is the process of collecting user-entered information, validating the data, and processing it when a user submits a form. React provides the onSubmit event, state management with useState(), and form data utilities such as FormData to handle submissions efficiently.

Course Link: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. Learning Objectives

After studying this topic, you will be able to:

  • Understand form submission in React JS.
  • Use the onSubmit event to handle form submissions.
  • Prevent the browser's default page reload using event.preventDefault().
  • Collect input values using React state and the FormData API.
  • Validate form data before submission.
  • Display success and error messages.
  • Reset form fields after submission.
  • Understand how to send form data to a backend API.

2. What Is Form Submission in React?

Form submission occurs when a user sends information entered into form fields by clicking a submit button or pressing Enter in an appropriate field. React allows developers to handle this process using event handlers attached to the HTML

element.

Common examples of forms include:

  • Login forms
  • Registration forms
  • Contact forms
  • Feedback forms
  • Job application forms
  • Course enrollment forms
  • Search forms

Basic HTML Form

<form>
  <input type="text" placeholder="Enter your name" />
  <button type="submit">Submit</button>
</form>

This form contains an input and a submit button. To process the submission within a React component, attach an event handler using onSubmit.


3. Understanding the onSubmit Event

The onSubmit event is triggered when a form is submitted. In React, it is commonly used to validate the form, process input values, display messages, or send data to an API.

Syntax

<form onSubmit={handleSubmit}>
  {/* Form fields */}
  <button type="submit">Submit</button>
</form>

Here, handleSubmit is the function that runs when the form is submitted.

Important Points

  • Attach onSubmit to the form rather than relying only on a button's click handler.
  • Use type="submit" for the button that submits the form.
  • Using the form's submit event supports both clicking the button and submitting through the keyboard.
  • Browser validation may run before the submit event when fields use attributes such as required or type="email".

4. Understanding event.preventDefault()

By default, the browser submits a traditional HTML form and may reload or navigate the page. When React handles the submission itself, event.preventDefault() prevents that default behavior.

Example

function ContactForm() {
  const handleSubmit = (event) => {
    event.preventDefault();
    alert("Form submitted successfully!");
  };
  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="name" placeholder="Enter your name" />
      <button type="submit">Submit</button>
    </form>
  );
}
export default ContactForm;

Explanation

  • onSubmit={handleSubmit} connects the form to the submission handler.
  • event represents the form submission event.
  • event.preventDefault() prevents the browser's default submission behavior.
  • The alert displays a message when the handler runs.

Note: Preventing the default behavior does not automatically save data. You must process the information locally or send it to a backend or API.


5. Form Submission Using useState()

The useState() Hook stores input values in React state. During submission, the handler can access the latest values and process them.

Example: Submit a Name

import { useState } from "react";
function NameForm() {
  const [name, setName] = useState("");
  const [submittedName, setSubmittedName] = useState("");
  const handleSubmit = (event) => {
    event.preventDefault();
    setSubmittedName(name);
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label htmlFor="name">Name:</label>
        <input
          id="name"
          type="text"
          value={name}
          onChange={(event) => setName(event.target.value)}
          required
        />
        <button type="submit">Submit</button>
      </form>
      {submittedName && (
        <p>Submitted Name: {submittedName}</p>
      )}
    </div>
  );
}
export default NameForm;

Explanation

  • name stores the current input value.
  • setName() updates the value as the user types.
  • handleSubmit() handles the form submission.
  • setSubmittedName(name) saves the submitted value in separate state.
  • The submitted name is displayed after submission.

6. Handling Multiple Form Fields

A form may contain several fields, such as name, email, phone number, and course selection. You can store related values in one state object and submit them together.

Example

import { useState } from "react";
function RegistrationForm() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: ""
  });
  const [submittedData, setSubmittedData] = useState(null);
  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((previousData) => ({
      ...previousData,
      [name]: value
    }));
  };
  const handleSubmit = (event) => {
    event.preventDefault();
    setSubmittedData({ ...formData });
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input name="name" value={formData.name}
          onChange={handleChange} placeholder="Enter name" required />
        <input name="email" type="email" value={formData.email}
          onChange={handleChange} placeholder="Enter email" required />
        <input name="phone" type="tel" value={formData.phone}
          onChange={handleChange} placeholder="Enter phone number" required />
        <button type="submit">Register</button>
      </form>
      {submittedData && (
        <div>
          <h3>Submitted Details</h3>
          <p>Name: {submittedData.name}</p>
          <p>Email: {submittedData.email}</p>
          <p>Phone: {submittedData.phone}</p>
        </div>
      )}
    </div>
  );
}
export default RegistrationForm;

Explanation: The form stores the values in formData. When submitted, it copies the current values into submittedData and displays the submitted details.


7. Collecting Form Values with FormData

The browser's FormData API allows you to collect values from form fields using their name attributes. It is especially useful for forms that do not need to store every input value in React state.

Example

function ContactForm() {
  const handleSubmit = (event) => {
    event.preventDefault();
    const formData = new FormData(event.currentTarget);
    const name = formData.get("name");
    const email = formData.get("email");
    console.log({ name, email });
  };
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name:</label>
      <input id="name" name="name" required />
      <label htmlFor="email">Email:</label>
      <input id="email" name="email" type="email" required />
      <button type="submit">Submit</button>
    </form>
  );
}
export default ContactForm;

Explanation

  • new FormData(event.currentTarget) collects successful form controls from the submitted form.
  • formData.get("name") retrieves the value associated with the name field.
  • formData.get("email") retrieves the email value.
  • Each field needs an appropriate name attribute to be included.

Important: Unchecked checkboxes and unselected radio buttons are not included as selected values in form data. For multiple values with the same name, use formData.getAll("fieldName"). For controlled inputs, reading values from React state is also a valid approach.


8. Form Validation Before Submission

Validation ensures that the user has entered the required information before the application processes the form. React forms can use built-in HTML validation and custom JavaScript checks.

Example: Required Fields

import { useState } from "react";
function LoginForm() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const handleSubmit = (event) => {
    event.preventDefault();
    if (!email.trim() || !password) {
      setError("Please enter your email and password.");
      setSuccess(false);
      return;
    }
    setError("");
    setSuccess(true);
  };
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email:</label>
      <input id="email" type="email" value={email}
        onChange={(event) => setEmail(event.target.value)} required />
      <label htmlFor="password">Password:</label>
      <input id="password" type="password" value={password}
        onChange={(event) => setPassword(event.target.value)} required />
      {error && <p role="alert">{error}</p>}
      {success && <p>Form validation passed.</p>}
      <button type="submit">Submit</button>
    </form>
  );
}
export default LoginForm;

Common Validation Rules

  • Check that required fields are not empty.
  • Validate email format.
  • Check that numeric values are within the permitted range.
  • Apply the required password policy.
  • Verify that required checkboxes are selected.
  • Display clear and accessible error messages.

Security Note: Client-side validation improves the user experience but can be bypassed. Always validate important data on the server as well.


9. Displaying Success and Error Messages

After processing a form, the application can display a success message or an error message. React state can control which message appears.

Example

import { useState } from "react";
function FeedbackForm() {
  const [message, setMessage] = useState("");
  const [status, setStatus] = useState("");
  const handleSubmit = (event) => {
    event.preventDefault();
    if (!message.trim()) {
      setStatus("error");
      return;
    }
    setStatus("success");
  };
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="message">Feedback:</label>
      <textarea id="message" value={message}
        onChange={(event) => setMessage(event.target.value)} />
      {status === "error" && (
        <p role="alert">Please enter your feedback.</p>
      )}
      {status === "success" && (
        <p role="status">Feedback submitted successfully!</p>
      )}
      <button type="submit">Send Feedback</button>
    </form>
  );
}
export default FeedbackForm;

This example demonstrates client-side validation and status messages. It does not send feedback to a server.


10. Resetting a Form After Submission

Controlled forms can be reset by restoring their state variables to the initial values. Uncontrolled forms can use the browser's reset functionality, or their fields can be managed through refs when needed.

Example: Resetting Controlled Inputs

import { useState } from "react";
const initialData = { name: "", email: "" };
function ContactForm() {
  const [formData, setFormData] = useState(initialData);
  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((previous) => ({
      ...previous,
      [name]: value
    }));
  };
  const handleSubmit = (event) => {
    event.preventDefault();
    console.log("Submitted:", formData);
    setFormData(initialData);
  };
  return (
    <form onSubmit={handleSubmit}>
      <input name="name" value={formData.name}
        onChange={handleChange} placeholder="Name" required />
      <input name="email" type="email" value={formData.email}
        onChange={handleChange} placeholder="Email" required />
      <button type="submit">Submit</button>
      <button type="button" onClick={() => setFormData(initialData)}>
        Reset
      </button>
    </form>
  );
}
export default ContactForm;

In a real application, reset the form only when appropriate, such as after a successful submission. If the submission fails, preserving the entered data can help the user correct the problem.


11. Sending Form Data to a Backend API

React handles the user interface, but saving information permanently usually requires a backend or API. You can send form data using the JavaScript fetch() function.

Example: Sending JSON Data

async function submitContactForm(formData) {
  const response = await fetch("/api/contact", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(formData)
  });
  if (!response.ok) {
    throw new Error("Failed to submit the form.");
  }
  return response.json();
}

Explanation:

  • fetch() sends a request to the API endpoint.
  • method: "POST" indicates that the request is intended to submit data.
  • Content-Type tells the server that the request body contains JSON.
  • JSON.stringify() converts the JavaScript object into JSON text.
  • response.ok checks whether the HTTP response status indicates success.

Important: The endpoint /api/contact is an example. Replace it with your actual backend endpoint. The server must validate and process the data.

Handling Loading, Success, and Failure

import { useState } from "react";
function ContactForm() {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState("idle");
  const [error, setError] = useState("");
  const handleSubmit = async (event) => {
    event.preventDefault();
    setStatus("submitting");
    setError("");
    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email })
      });
      if (!response.ok) {
        throw new Error("Unable to submit the form.");
      }
      setStatus("success");
    } catch (err) {
      setStatus("error");
      setError(err.message || "Something went wrong.");
    }
  };
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email:</label>
      <input id="email" type="email" value={email}
        onChange={(event) => setEmail(event.target.value)} required />
      <button type="submit" disabled={status === "submitting"}>
        {status === "submitting" ? "Submitting..." : "Submit"}
      </button>
      {status === "success" && (
        <p role="status">Form submitted successfully!</p>
      )}
      {error && <p role="alert">{error}</p>}
    </form>
  );
}
export default ContactForm;

This example illustrates asynchronous submission states. It assumes the API returns an appropriate successful HTTP status. In a production application, handle server validation errors and unexpected responses according to the backend's response format.


12. Controlled Forms vs. FormData

Feature Controlled Form FormData Approach
Value management React state manages values Values are read from form controls at submission time
Typical properties value, checked, onChange name attributes and new FormData()
Live UI updates Easy to implement Requires additional event handling if needed
Validation while typing Convenient Possible, but usually requires reading field values separately
Submission Read values from state Read values using formData.get()
Typical use Interactive forms with dynamic behavior Simple forms where values are needed mainly on submission

13. Common Mistakes and Solutions

Mistake Solution
Forgetting event.preventDefault() Prevent the browser's default submission when processing the form in React.
Attaching submission logic only to a button click Use the form's onSubmit handler to support keyboard submission and form validation.
Missing name attributes with FormData Add a meaningful name to every field whose value must be collected.
Submitting empty fields Use HTML validation and custom validation where appropriate.
Assuming data is saved automatically Send the validated data to a backend or API when persistence is required.
Not handling API errors Check the response status and handle rejected requests with try...catch.
Using a default button type unintentionally Specify type="submit" or type="button" explicitly.
Clearing fields before a request succeeds Consider resetting the form only after a successful response.

14. Best Practices for Form Submission

  • Use the onSubmit event on the form element.
  • Call event.preventDefault() when React should handle submission without a page reload.
  • Use appropriate input types and labels.
  • Validate the information before processing it.
  • Display accessible loading, success, and error messages.
  • Disable the submit button while a request is in progress when appropriate.
  • Handle network errors and unsuccessful HTTP responses.
  • Validate submitted data on the server as well as in the browser.
  • Use HTTPS for transmitting sensitive information.
  • Never store passwords or other sensitive information in plain text or unnecessary logs.
  • Reset form fields only when it makes sense for the user experience.

15. Practical Project: Student Registration Form

Create a registration form that collects a student's name, email, phone number, and selected course. Validate required fields, submit the data, and display the submitted details.

Complete Example

import { useState } from "react";
const initialData = {
  name: "",
  email: "",
  phone: "",
  course: ""
};
function StudentRegistration() {
  const [formData, setFormData] = useState(initialData);
  const [submittedData, setSubmittedData] = useState(null);
  const [error, setError] = useState("");
  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((previousData) => ({
      ...previousData,
      [name]: value
    }));
  };
  const handleSubmit = (event) => {
    event.preventDefault();
    if (
      !formData.name.trim() ||
      !formData.email.trim() ||
      !formData.phone.trim() ||
      !formData.course
    ) {
      setError("Please complete all required fields.");
      return;
    }
    setError("");
    setSubmittedData({ ...formData });
  };
  const handleReset = () => {
    setFormData(initialData);
    setSubmittedData(null);
    setError("");
  };
  return (
    <div>
      <h2>Student Registration</h2>
      <form onSubmit={handleSubmit}>
        <label htmlFor="name">Full Name:</label>
        <input id="name" name="name" value={formData.name}
          onChange={handleChange} required />
        <label htmlFor="email">Email:</label>
        <input id="email" name="email" type="email"
          value={formData.email} onChange={handleChange} required />
        <label htmlFor="phone">Phone Number:</label>
        <input id="phone" name="phone" type="tel"
          value={formData.phone} onChange={handleChange} required />
        <label htmlFor="course">Select Course:</label>
        <select id="course" name="course" value={formData.course}
          onChange={handleChange} required>
          <option value="">Choose a course</option>
          <option value="React JS">React JS</option>
          <option value="Flutter">Flutter</option>
          <option value="Figma">Figma</option>
        </select>
        {error && <p role="alert">{error}</p>}
        <button type="submit">Register</button>
        <button type="button" onClick={handleReset}>Reset</button>
      </form>
      {submittedData && (
        <div>
          <h3>Submitted Registration Details</h3>
          <p>Name: {submittedData.name}</p>
          <p>Email: {submittedData.email}</p>
          <p>Phone: {submittedData.phone}</p>
          <p>Course: {submittedData.course}</p>
        </div>
      )}
    </div>
  );
}
export default StudentRegistration;

Project Features

  • Collects multiple student details.
  • Manages fields using a single state object.
  • Validates required fields.
  • Handles form submission with onSubmit.
  • Displays submitted information.
  • Provides a reset option.

Project Outcome: This project demonstrates client-side form submission. It does not store the data in a database; backend integration is required for persistent storage.


16. Interview Questions and Answers

Q1. What is form submission in React?

Form submission is the process of handling the information entered by a user when they submit a form.

Q2. What is the purpose of onSubmit?

The onSubmit event handler runs when a form is submitted and can be used to validate or process the data.

Q3. Why do we use event.preventDefault()?

It prevents the browser's default form submission behavior, allowing React to process the form without the default page reload or navigation.

Q4. How can you get form values in React?

You can read controlled values from React state or collect form control values using the FormData API.

Q5. What is the difference between onSubmit and onClick?

onSubmit handles form submission, including submission through the keyboard. onClick handles a click on a particular element and is not a complete replacement for form submission handling.

Q6. How do you validate a form before submission?

Use built-in HTML validation attributes and custom validation logic to check the values before processing them.

Q7. How can form data be sent to a server?

Use an HTTP request, such as fetch() with a POST method, to send data to a backend API.

Q8. How do you display a success message?

Store the submission status in React state and conditionally render a success message when the operation succeeds.

Q9. How can a form be reset?

For controlled inputs, reset the associated state to the initial values. Uncontrolled forms can use native reset behavior.

Q10. Is client-side validation enough for security?

No. Client-side validation improves usability, but the server must independently validate data before processing or storing it.


17. Practice Exercises

  1. Create a form that collects a user's name and displays it after submission.
  2. Create a login form with email and password validation.
  3. Build a contact form with name, email, subject, and message fields.
  4. Use FormData to collect uncontrolled form values.
  5. Display an error when a required field is empty.
  6. Show a success message after a valid form submission.
  7. Add a reset button to clear all controlled input fields.
  8. Simulate an API request and display loading, success, and error states.

18. Quick Revision Checklist

  • Understand the purpose of form submission in React.
  • Know how to use the onSubmit event.
  • Understand event.preventDefault().
  • Know how to access controlled input values from state.
  • Understand the FormData API and field names.
  • Implement form validation and error messages.
  • Handle success, failure, and loading states.
  • Know how to reset controlled form fields.
  • Understand how to send data to a backend API.
  • Follow accessibility and security best practices.

19. Conclusion

Form Submission is an essential React JS concept used to collect, validate, and process user information. By learning the onSubmit event, event.preventDefault(), React state, the FormData API, and backend integration, developers can build interactive forms for registration, login, feedback, contact, and many other applications.

Explore more concepts through JustAcademy React JS Training Course or register using Register for React JS Course Demo.

whatsapp